package notes.java.concurrent;

/**
 * 死锁示例
 * @author wangcs
 *
 */
public class U14_TestDeadLock implements Runnable{

	public  int flag = 0;
	private static Object o1 = new Object(), o2 = new Object();
	
	@Override
	public void run() {
		if(flag == 0) {
			// 先加锁o1
			synchronized (o1) {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 再加锁o2
				synchronized (o2) {
					System.out.println("o2");
				}
			}
			
		}
		if(flag == 1) {
			// 先加锁o2
			synchronized (o2) {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 再加锁o1
				synchronized (o1) {
					System.out.println("o1");
				}
			}
			
		}
	}
	
	public static void main(String[] args) {
		U14_TestDeadLock deadLock = new U14_TestDeadLock();
		deadLock.flag = 0;
		
		U14_TestDeadLock deadLock2 = new U14_TestDeadLock();
		deadLock2.flag = 1;
		
		new Thread(deadLock).start();
		new Thread(deadLock2).start();
	}

}
